package com.peza.bikelog.common.domain.polar;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import com.peza.bikelog.common.util.Util;

public class HrmHrData implements Writable {

	
	private static Util util = Util.getInstance();
	
	private List<Sample> samples = new ArrayList<Sample>();
	
	public HrmHrData(){	}
	
	public HrmHrData(String data){	
		this(data, null);
	}
	
	public HrmHrData(String data, Float avs){
		List<String>lines = Arrays.asList(data.split("\n"));
		Iterator<String> iter = lines.iterator();
		int speed = 0;
		if (avs != null){
			speed = (int) (10 * avs);
		}
		while(iter.hasNext()){
			String line = iter.next();
			Sample sample = new Sample();
			String [] cells = line.split("\t");
			
			if (cells.length > 2){
				sample.setBpm(util.convertToInt(cells[0]));
				sample.setSpeed(util.convertToInt(cells[1]));
				sample.setAltitude(util.convertToInt(cells[2]));
			} else if (cells.length == 2) {
				try {
					sample.setBpm(util.convertToInt(cells[0]));
					sample.setSpeed(speed);
					sample.setAltitude(util.convertToInt(cells[1]));
				} catch (Exception e) {
					System.err.println(e);
				}
			} else {
				// do nothing
			}
			
			samples.add(sample);
		}	
		
	}
	
	@SuppressWarnings("unused")
	public class Sample {
		private int bpm;
		private int speed; //x10
		private int altitude;
		
		public int getBpm() {
			return bpm;
		}
		public void setBpm(int bpm) {
			this.bpm = bpm;
		}
		public int getSpeed() {
			return speed;
		}
		public void setSpeed(int speed) {
			this.speed = speed;
		}
		public int getAltitude() {
			return altitude;
		}
		public void setAltitude(int altitude) {
			this.altitude = altitude;
		} 
	}

	public List<Sample> getSamples() {
		return samples;
	}

	public void setSamples(List<Sample> samples) {
		this.samples = samples;
	}

	@Override
	public String toFileString() {
		StringBuffer buffer = new StringBuffer("[HRData]\n");
		
		for (Sample sample : samples){
			buffer.append(sample.getBpm() + "\t");
			buffer.append(sample.getSpeed() + "\t");
			buffer.append(sample.getAltitude() + "\n");
			
		}
		buffer.append("\n");
		return buffer.toString();
	}

	public void setAverageSpeed(int avsInt) {
		for (Sample sample : samples){
			sample.setSpeed(avsInt);
			
		}
	}
	
	
	
	
}
